package com.yiyun.blog.service.mq;

import com.alibaba.fastjson.JSON;
import com.yiyun.blog.dao.pojo.Article;
import com.yiyun.blog.service.ArticleService;
import com.yiyun.blog.vo.ArticleMessage;
import com.yiyun.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Set;

/**
 * @author Bao
 * @create 2022-05-16-15:37
 *
 * rocketMQTemplate.convertAndSend("blog-update-article",articleMessage)
 * topic：blog-update-article
 * consumerGroup：要有多台服务器会用到，加入一个组中，工作效率高
 */
@Slf4j
//@Component
@RocketMQMessageListener(topic = "blog-update-article", consumerGroup = "blog-article-group")
public class ArticleListener implements RocketMQListener<ArticleMessage> {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void onMessage(ArticleMessage articleMessage) {
        log.info("收到消息:{}", articleMessage);
        // 接下来要做的事 更新缓存
        // 1.更新查看文章详情的缓存
        Long articleId = articleMessage.getArticleId();
        String params = DigestUtils.md5Hex(String.valueOf(articleId));
        String redisKey = "view_article::ArticleController::findArticleById::"+params;
        Result articleResult = articleService.findArticleById(articleId);
        redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(articleResult), Duration.ofMillis(1 * 60 * 1000));
        log.info("更新了缓存:{}", redisKey);
        // 2. 文章列表的 缓存 不知道参数，解决的方法  直接删除缓存（不建议使用）
        Set<String> keys = redisTemplate.keys("listArticle*");
        keys.forEach(key ->{
            redisTemplate.delete(key);
            log.info("删除了文章列表的缓存", key);
        });
    }
}
